---
title: I2C
sidebar_position: 50
---

# I2C

I2C [builtin package](/developer/packages) that exposes
a [I2C service](/api/clients/i2c/) to interact with I2C devices.

```ts skip
import { i2c } from "@devicescript/i2c"

const address = 0x..
const register = 0x..
const value = 0x..

// highlight-next-line
await i2c.writeReg(address, register, value)

// highlight-next-line
const readValue = await i2c.readReg(address, register)
```

## Driver

The `I2CDriver` and `I2CSensorDriver` classes encapsulate storing the address and generally handles a bit of the
low-level I2C protocol. It is not required to use the driver, but it can be useful.

```ts skip title="./aht20.ts"
import { I2CSensorDriver } from "@devicescript/drivers"

const AHT20_ADDRESS = 0x38
const AHT20_BUSY = 0x80
const AHT20_OK = 0x08
const AHT20_READ_THROTTLE = 500

class AHT20Driver extends I2CSensorDriver<{
    humidity: number
    temperature: number
}> {
    constructor() {
        super(AHT20_ADDRESS, { readCacheTime: AHT20_READ_THROTTLE })
    }

    // ...

    override async readData() {
        await this.writeBuf(hex`AC3300`)
        await this.waitBusy()
        const data = await this.readBuf(6)

        const h0 = (data[1] << 12) | (data[2] << 4) | (data[3] >> 4)
        const humidity = h0 * (100 / 0x100000)
        const t0 = ((data[3] & 0xf) << 16) | (data[4] << 8) | data[5]
        const temperature = t0 * (200.0 / 0x100000) - 50

        return { humidity, temperature }
    }
}
```

You can find implementation examples at https://github.com/microsoft/devicescript/tree/main/packages/drivers/src.

